package studio.xiaoyun.web.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;
import studio.xiaoyun.common.convert.FileConverter;
import studio.xiaoyun.core.Config;
import studio.xiaoyun.core.exception.CoreException;
import studio.xiaoyun.core.exception.ErrorCode;
import studio.xiaoyun.web.RestResult;
import studio.xiaoyun.web.resource.UploadFileResource;
import studio.xiaoyun.web.restController.FileRestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

@Controller
@RequestMapping("/v1/file")
public class FileController {
    @Resource
    private FileRestController fileRestController;
    @Resource
    private FileConverter fileConverter;

    /**
     * 上传文件并预览文件
     * @param file 上传的文件
     */
    @RequestMapping(value = "/preview")
    public void uploadAndPreviewFile(HttpServletRequest request, HttpServletResponse response,MultipartFile file) throws Exception{
        RestResult restResult = fileRestController.uploadFile(file);
        @SuppressWarnings("rawtypes")
		UploadFileResource resource = (UploadFileResource) ((List) restResult.getModelMap().get(RestResult.KEY_ROWS)).get(0);
        previewFileByFileName(request,response,resource.getUrl());
    }

    /**
     * 根据文件路径预览文件
     * @param file 文件地址
     */
    @RequestMapping(value = "/previewFile")
    public void previewFileByFileName(HttpServletRequest request, HttpServletResponse response,String file) throws Exception{
        if(file.startsWith("/")){
            file = file.substring(1);
        }
        String fileName = Config.getBasePath()+file;
        //只能预览临时目录中的文件
        if(!fileName.startsWith(Config.getUploadPath())){
            throw new CoreException(ErrorCode.PARAMETER_ERROR,"文件不存在");
        }
        String htmlFileName = fileConverter.toHtml(fileName);  //将文件转换为html
        htmlFileName = htmlFileName.substring(Config.getBasePath().length());
        String path = request.getContextPath();
        String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
        String url = basePath+htmlFileName;
        response.sendRedirect(url);
    }

}
